﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace httpLibrary
{
    public class HtmlContextObj
    {
        public string Id { get; set; }

        public string Url { get; set; }

        public string Title { get; set; }

        public DateTime PostDate { get; set; }

        public string Content { get; set; }

        public string ParentId { get; set; }

        public int Flag { get; set; }

        public bool SetHtmlDate(string htmlstr)
        {
            bool rs = false;

            if (string.IsNullOrWhiteSpace(htmlstr) == false)
            {
                PostDate = DateTime.Now;
                Content = CsharpHttpHelper.HttpHelper.StripHTML(htmlstr);
                Title = CsharpHttpHelper.HttpHelper.GetHtmlTitle(htmlstr);
                Flag = 1;
                if(string.IsNullOrWhiteSpace(Content) == false)
                {
                    rs = true;
                }
            }

            Flag = 1;

            return rs;
        }

        /// <summary>
        /// 获取html文档的标题(Title) by 何问起
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string GetTitle(string html)
        {
            string h_title = "";

            string pattern = @"(?si)<title(?:\s+(?:""[^""]*""|'[^']*'|[^""'>])*)?>(?<title>.*?)</title>";
            h_title = Regex.Match(html, pattern).Groups["title"].Value.Trim();

            return h_title;
        }

        /// <summary>
        /// 过滤html标签
        /// </summary>
        /// <param name="strHtml">html的内容</param>
        /// <returns></returns>
        public static string StripHTML(string stringToStrip)
        {
            // paring using RegEx           //
            stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            stringToStrip = Regex.Replace(stringToStrip, "", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            stringToStrip = StripHtmlXmlTags(stringToStrip);
            return stringToStrip;
        }
        private static string StripHtmlXmlTags(string content)
        {
            return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }
    }
}
